package org.example.com.pattern.structure.composite

/**
 * 结构型模式-组合模式
 * 组合模式是一种结构型模式，可以使用它将对象组合成树状结构，并能像使用独立对象一样使用它们。
 * 场景：如果应用的核心模型能用树型结构表示，使用组合模式才会有价值
 */
interface Graphic {
    fun move(x: Int, y: Int)
    fun draw()
}

class Dot(x: Int, y: Int) : Graphic {
    private var x = x
    private var y = y
    override fun move(x: Int, y: Int) {
        this.x += x
        this.y += y
    }

    override fun draw() {
        println("Dot draw...")
    }
}

class Circle(x: Int, y: Int, val radius: Int) : Graphic {
    private var x = x
    private var y = y
    override fun move(x: Int, y: Int) {
        this.x += x
        this.y += y
    }

    override fun draw() {
        println("Circle draw...")
    }
}

class CompoundGraphic : Graphic {
    private val children = mutableListOf<Graphic>()
    fun add(graphic: Graphic) {
        children.add(graphic)
    }

    fun remove(graphic: Graphic) {
        children.remove(graphic)
    }

    override fun move(x: Int, y: Int) {
        children.forEach {
            it.move(x, y)
        }
    }

    override fun draw() {
    }
}

class ImageEditor {
    private var all: CompoundGraphic? = null
    fun load() {
        all = CompoundGraphic()
        all!!.add(Circle(5, 3, 10))
        all!!.add(Dot(1, 2))
    }

    fun groupSelected(components: List<Graphic>) {
        val group = CompoundGraphic()
        components.forEach {
            group.add(it)
            all?.remove(it)
        }
        all?.add(group)
        all?.draw()
    }
}